﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;

namespace Conmmon
{
    public static class ConfigHelper
    {

        private static IConfiguration _configuration;

        static ConfigHelper()
        {
            //在当前目录或者根目录中寻找appsettings.json文件
            var fileName = "appsettings.json";

            var directory = AppContext.BaseDirectory;
            directory = directory.Replace("\\", "/");

            var filePath = $"{directory}/{fileName}";
            if (!File.Exists(filePath))
            {
                var length = directory.IndexOf("/bin");
                filePath = $"{directory.Substring(0, length)}/{fileName}";
            }

            var builder = new ConfigurationBuilder()
                .AddJsonFile(filePath, false, true);

            _configuration = builder.Build();
        }

        /// <summary>
        /// 非默认配置文件初始化
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static IConfiguration GetConfiguration(string fileName)
        {
           var fileNames =  fileName.Split('.');

            if (fileNames[fileNames.Length -1] != "json") {

                throw new Exception("只能读取JSON"); 
            }

            //在当前目录或者根目录中寻找fileName文件

            var directory = AppContext.BaseDirectory;
            directory = directory.Replace("\\", "/");

            var filePath = $"{directory}/{fileName}";
            if (!File.Exists(filePath))
            {
                var length = directory.IndexOf("/bin");
                filePath = $"{directory.Substring(0, length)}/{fileName}";
            }

            var builder = new ConfigurationBuilder()
                .AddJsonFile(filePath, false, true);

            return builder.Build();
        }

        /// <summary>
        /// 通过KEY获取配置文件中的数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetSectionValue(string key)
        {
            return _configuration.GetSection(key).Value;
        }

        /// <summary>
        /// 通过KEY获取配置文件中的数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="fileName">配置文件相对路径</param>
        /// <returns></returns>
        public static string GetSectionValue(string key, string fileName)
        {
            return GetConfiguration(fileName).GetSection(key).Value;
        }


        /// <summary>
        /// 将配置文件转换为实体
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="key">配置文件KEY</param>
        /// <returns></returns>
        public static T GetSectionValue<T>(string key) where T : class, new()
        {
            T t = new T();
            Type type = t.GetType();

            var properties = type.GetProperties();

            foreach (var item in properties)
            {
                item.SetValue(t, GetSectionValue($"{key}:{item.Name}"));
            }
            return t;
        }

        /// <summary>
        /// 将配置文件转换为实体
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="key">配置文件KEY</param>
        /// <param name="fileName">配置文件相对路径（只支持JSON）</param>
        /// <returns></returns>
        public static T GetSectionValue<T>(string key,string fileName) where T : class, new()
        {
            T t = new T();
            Type type = t.GetType();

            var properties = type.GetProperties();

            foreach (var item in properties)
            {
                item.SetValue(t, GetSectionValue($"{key}:{item.Name}",fileName));
            }
            return t;
        }

    }
}

